package cn.com.dhcc.turbo.web.controller.monitor;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.com.dhcc.app.core.base.BaseController;
import cn.com.dhcc.app.core.handler.modulehandler.WhereCondition;
import cn.com.dhcc.app.core.handler.modulehandler.valuebean.BetweenValue;
import cn.com.dhcc.app.core.handler.pagerhandler.Pager;
import cn.com.dhcc.app.core.handler.pagerhandler.PagerData;
import cn.com.dhcc.app.core.service.Log;
import cn.com.dhcc.app.core.service.Log.LOGTYPE;
import cn.com.dhcc.app.core.util.DTUtil;
import cn.com.dhcc.app.core.util.StrUtil;
import cn.com.dhcc.app.core.util.XstreamUtil;
import cn.com.dhcc.app.pub.core.annotation.TurboMenu;
import cn.com.dhcc.app.pub.core.consts.AppConst;
import cn.com.dhcc.app.pub.core.consts.NodeInfoParam;
import cn.com.dhcc.app.pub.core.tag.AppTagEl;
import cn.com.dhcc.turbo.entity.api.RouteLog;
import cn.com.dhcc.turbo.entity.exch.SendFileData;
import cn.com.dhcc.turbo.entity.registry.NodeInfo;
import cn.com.dhcc.turbo.entity.sysmgr.UserInfo;
import cn.com.dhcc.turbo.entity.sysmgr.UserInfo.SL_AUTH_FLAG;
import cn.com.dhcc.turbo.service.exch.filedata.SendFileDataService;
import cn.com.dhcc.turbo.service.registry.BaseInfoService;
import cn.com.dhcc.turbo.service.registry.NodeInfoService;

@Controller
@RequestMapping("/monitor")
@TurboMenu(belongToMenu = TurboMenu.LEAF_MENU.UNSTRUC_MONITOR_SEND)
public class SendFileDataController extends BaseController {
    @SuppressWarnings("deprecation")
	private static Logger logger = Log.getExistLogger(LOGTYPE.SAI);

    @Autowired
    private SendFileDataService sendFileDataService;
    @Autowired
    private NodeInfoService nodeInfoService;
   
    @Autowired
    private BaseInfoService baseInfoService;
    @RequestMapping(value = "/send_file_data_list")
    public String list(
            Model model,
            Pager pager,
            HttpServletRequest request,
            String sendNodecode,
            String sendAdaptercode,
            String recvNodecode,
            String sendStatus,
            String notifyStatus,
            String startCreated,
            String endCreated,
            String orderName,
            String order) {
        try {
            UserInfo userInfo = (UserInfo)BaseController.getCurrentUserInfo(request.getSession());
			boolean isSysUser = userInfo.getSlAuthFlag().equalsIgnoreCase(SL_AUTH_FLAG.SYS_USER.getCode());
			NodeInfo localNode=nodeInfoService.getLocalNode();
			List<Map<String,String>> sendNodeList=new ArrayList<Map<String,String>>();
			List<Map<String,String>> sendAdapterList=new ArrayList<Map<String,String>>();

            WhereCondition searchData = new WhereCondition();
            searchData.where().eq("1", "1");

            if (StrUtil.isNotBlank(notifyStatus)) {
				searchData.and().like("NOTIFY_STATUS", notifyStatus);
			}
            
            if (StrUtil.isNotBlank(sendNodecode)) {
                searchData.and().like("send_nodecode", sendNodecode);
            }else if (isSysUser) {
				searchData.and().like("send_nodecode", baseInfoService.getCurrentNodeInfo().getNodeCode());
				searchData.and().like("send_adaptorcode", userInfo.getUserName());
				
				//默认选择项
				Map<String,String> sendNodeMap=new HashMap<String, String>();
				sendNodeMap.put("code", localNode.getNodeCode());
				sendNodeMap.put("name", localNode.getNodeName());
				sendNodeList.add(sendNodeMap);
				//默认选择项
				//默认选择项
				Map<String,String> sendAdapterMap=new HashMap<String, String>();
				sendAdapterMap.put("code", userInfo.getUserName());
				sendAdapterMap.put("name", AppTagEl.adaptorName(userInfo.getUserName()));
				sendAdapterList.add(sendAdapterMap);
			}
            
            if (StrUtil.isNotBlank(sendAdaptercode)) {
                searchData.and().like("send_adaptorcode", sendAdaptercode);
            }
            if (StrUtil.isNotBlank(recvNodecode)) {
                searchData.and().like("recv_nodecode", recvNodecode);
            }
            

            if (StrUtil.isNotBlank(sendStatus)) {
                searchData.and().eq("send_status", sendStatus);
            }
            //时间范围从那天到那天
            //时间范围从那天到那天
            if (StrUtil.isNotBlank(startCreated) && StrUtil.isNotBlank(endCreated)) {
                searchData.and().between("modified", new BetweenValue(DTUtil.toDateTime(startCreated) , DTUtil.toDateTime(endCreated)));
            }

            //时间范围，大于等于某天
            if (StrUtil.isNotBlank(startCreated) && StrUtil.isBlank(endCreated)) {
                searchData.and().between("modified", new BetweenValue(DTUtil.toDateTime(startCreated), null, true, false));
            }

            //时间范围，小于等于某天
            if (StrUtil.isBlank(startCreated) && StrUtil.isNotBlank(endCreated)) {
                searchData.and().between("modified", new BetweenValue(null, DTUtil.toDateTime(endCreated), false, true));
            }
            if (StrUtil.isNotBlank(orderName)) {
                searchData.orderBy(orderName + " " + order);
            } else {
                searchData.orderBy("modified  desc");
            }
            PagerData<SendFileData> datas = sendFileDataService.getPagerList(pager, searchData);
            model.addAttribute("localNode", localNode);
            model.addAttribute(DATA_KEY, datas.getDatas());
            
            if (isSysUser && sendFileDataService.getSendNodeList().size()<=0) {
				model.addAttribute("send_node_list", sendNodeList);
			}else{
				model.addAttribute("send_node_list", sendFileDataService.getSendNodeList());
			}
            
            
            if (isSysUser && sendFileDataService.getSendAdapterList().size()<=0) {
				model.addAttribute("send_adapter_list", sendAdapterList);
			}else{
				model.addAttribute("send_adapter_list", sendFileDataService.getSendAdapterList());
			}
            
			model.addAttribute("recv_node_list", sendFileDataService.getRecvNodeList());
			model.addAttribute("notify_status_list", AppConst.NotifyStatus.values());
            model.addAttribute("send_status_list", AppConst.SendStatus.values());
            setTotoal(model, datas.getTotal());
            return "monitor/send_file_data_list";
        } catch (Exception e) {
            logger.error("操作失败", e);
            return toAlertPage(model, e.getMessage());
        }
    }

    /**
     * 根据nodecode获取sysinfoList
     *
     * @param nodecode
     * @return
     */
	@RequestMapping(value = "/get_sysinfo_nodecode")
    @ResponseBody
    public Map<String, Object> getSysInfoByNodeCode(String nodecode) {
        if (nodecode == null) {
            return jsonSuccessDataResult("获取成功", null);
        }
        try {
//            NodeInfo nodeInfo = nodeInfoService.getNodeInfoByNodeCode(nodecode);
            //List<SysInfo> sysInfoList = sysInfoService.getSysInfoByNodeId(nodeInfo.getId());
            return null;//jsonSuccessDataResult("获取成功", sysInfoList);
        } catch (Exception e) {
            logger.error("获取失败", e);
            return jsonFailResult("获取失败");
        }
    }

    /**
     * 查看页面
     *
     * @param model
     * @param id
     * @return
     */
	@RequestMapping(value = "/send_file_data_get")
    public String get(Model model, String id) {
        try {
            SendFileData vo = sendFileDataService.get(id);
            String payload = vo.getPayload();
            String path = AppConst.CMDATA_STORED_DIR + File.separator + payload;
            File file = new File(path);
            if (file.exists()) {
//                String payloadContent = FileUtils.readFileToString(file);
                //vo.setPayloadContent(payloadContent);
            } else {
                model.addAttribute("payloadError", "数据报文文件[" + path + "]不存在");
            }

            String routeLogXml = vo.getRoutelog();
            RouteLog routeLog = XstreamUtil.toObject(RouteLog.class,routeLogXml);
            model.addAttribute("netType", NodeInfoParam.NODE_NET_TYPE);
            model.addAttribute(DATA_KEY, vo);
            model.addAttribute("routeLog", routeLog);
            return "monitor/send_file_data_get";
        } catch (Exception e) {
            logger.error("操作失败", e);
            return toAlertPage(model, e.getMessage());
        }
    }

    /**
     * 新增页面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/send_file_data_add")
    public String add(Model model) {
        try {
            return "monitor/send_file_data_add";
        } catch (Exception e) {
            logger.error("操作失败", e);
            return toAlertPage(model, e.getMessage());
        }
    }

    /**
     * 根据ID删除记录
     *
     * @param model
     * @param id
     * @return
     */
    @RequestMapping(value = "/send_file_data_delete", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> add(Model model, String id) {
        try {
            sendFileDataService.delete(id);
            return jsonSuccessResult("删除成功");
        } catch (Exception e) {
            logger.error("删除失败", e);
            return jsonFailResult("删除失败");
        }
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @RequestMapping(value = "/send_file_data_deletes", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> deleteByIds(@RequestParam("ids") String ids) {
        String msg = "";
        try {
            msg = "删除成功";
            sendFileDataService.deleteBatchById(ids.split(","));
            return jsonSuccessResult(msg);
        } catch (Exception e) {
            msg = "删除系统信息失败";
            logger.error(msg, e);
            return jsonFailResult(e.getMessage());
        }
    }
}
